package com.aiapphub.BaseCode.runner;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.aiapphub.BaseCode.entity.SsoOrg;
import com.aiapphub.BaseCode.service.SsoOrgService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.aiapphub.BaseCode.utils.TokenUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.format.DateTimeFormatter;
import java.io.IOException;
import java.time.LocalDateTime;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

@Service
public class SSOOrgDataSync {

    private static final Logger logger = LoggerFactory.getLogger(SSOOrgDataSync.class);

    @Autowired
    private RestTemplate restTemplate; // 注入 RestTemplate

    @Autowired
    private TokenUtil tokenUtil;

    @Value("${sso.data.url.orgData}")
    private String orgDataUrl; // 组织数据API URL

    private String accessToken; // 存储访问令牌

    private final ObjectMapper objectMapper = new ObjectMapper(); // 复用 ObjectMapper 实例

    @Autowired
    private SsoOrgService orgService;

    // 定时调用组织部门数据API
    // 恢复定时任务注解以启用SSO同步
    @Scheduled(cron = "0 */5 * * * ?") // 每5分钟执行一次
    public void orgDataSync() {
        try {
            accessToken = tokenUtil.fetchToken(); // 使用 TokenUtil 获取访问令牌
        } catch (IOException e) {
            logger.error("获取TOKEN失败", e);
            return;
        }
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json");
            headers.set("Authorization", "Bearer " + accessToken);
            String currentDateTime = LocalDateTime.now().minusMinutes(5)
                    .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            //String currentDateTime = LocalDateTime.now().minusYears(2)
            //        .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String requestJson = String.format("{\"dateTime\": \"%s\", \"orgSn\": \"\", \"pageNo\": 1, \"pageSize\": 1000, \"extraAttrs\": 1}", currentDateTime);
            HttpEntity<String> requestEntity = new HttpEntity<>(requestJson, headers);
            ResponseEntity<String> response = restTemplate.exchange(orgDataUrl, HttpMethod.POST, requestEntity, String.class);
            if (response.getStatusCode().is2xxSuccessful()) {
                handleApiResponse(response);
                logger.info("API 调用成功，时间: {}", LocalDateTime.now().minusMinutes(5).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            } else {
                logger.warn("API 调用失败，状态码: {}", response.getStatusCode());
            }
        } catch (Exception e) {
            logger.error("调用 API 失败", e);
        }
    }

    private void handleApiResponse(ResponseEntity<String> response) {
        if (response.getStatusCode().is2xxSuccessful()) {
            logger.info("API 响应: {}", response.getBody());
            try {
                processApiResponse(response.getBody());
            } catch (IOException e) {
                logger.error("解析 API 响应失败: {}", e.getMessage());
            }
        } else {
            logger.warn("API 调用失败，状态: {}, 内容: {}", response.getStatusCode(), response.getBody());
        }
    }

    private void processApiResponse(String responseBody) throws IOException {
        JsonNode rootNode = objectMapper.readTree(responseBody);
        JsonNode dataNode = rootNode.path("data");
        if (dataNode.isArray()) {
            for (JsonNode node : dataNode) {
                try {
                    SsoOrg ssoOrg = objectMapper.treeToValue(node, SsoOrg.class);
                    processOrg(ssoOrg); // 处理组织
                } catch (JsonProcessingException e) {
                    logger.error("组织解析失败: {}, 数据: {}", e.getMessage(), node.toString());
                }
            }
            logger.info("处理完成，共处理 {} 个组织。", dataNode.size());
        } else {
            logger.warn("数据节点不是数组，内容: {}", dataNode.toString());
        }
    }

    private void processOrg(SsoOrg ssoOrg) {
        QueryWrapper<SsoOrg> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", ssoOrg.getOrgId());
        if (orgService.count(queryWrapper) > 0) {
            orgService.update(ssoOrg, queryWrapper);
            logger.info("更新组织: {}", ssoOrg.getOrgName());
        } else {
            orgService.save(ssoOrg);
            logger.info("成功新增组织: {}", ssoOrg.getOrgName());
        }
    }
}